<template>
  <div class="connection-data">
    <el-card shadow="hover" style="margin-bottom: 16px;">
      <div style="display: flex; flex-direction: row;">
        <span v-if="connection.running" class="success-status">
          连接成功
        </span>
        <span v-else class="error-status">
          连接失败
        </span>
        <span class="connection-info">
          {{ formatTimestampString(connection.createTime) }}
        </span>
        <el-button size="medium" icon="el-icon-document" style="margin-left: auto;" @click="drawerVisible = true">
          详情
        </el-button>
        <el-button size="medium" icon="el-icon-switch-button" @click="closeConnection">
          关闭连接
        </el-button>
      </div>
    </el-card>
    <el-tabs type="border-card" v-model="tabIndex" @tab-remove="closeTable">
      <el-tab-pane name="table" label="表" lazy>
        <Table :connection-id="connectionId" :tables="tables" @open-table="openTable" @update="setTables"></Table>
      </el-tab-pane>
      <el-tab-pane v-for="tablePane in tablePanes" :key="tablePane.tabIndex" :name="tablePane.tabIndex"
        :label="tablePane.name" closable lazy>
        <Data :connection-id="connectionId" :table-name="tablePane.name" :families="tablePane.families"></Data>
      </el-tab-pane>
    </el-tabs>
    <el-drawer title="详情" :visible.sync="drawerVisible" direction="rtl">
      <div style="padding-left: 20px; padding-right: 20px;">
        <el-descriptions :column="1" :border="true" direction="vertical">
          <el-descriptions-item label="标识符">
            <span class="value">{{ connection.id }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <span class="value">{{ connection.running ? '正常' : '断开' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            <span class="value" @click="copyText(formatTimestampString(connection.createTime))">
              {{ formatTimestampString(connection.createTime) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item v-for="param in params" :key="param.name" :label="param.name">
            <span class="value" @click="copyText(param.value)">{{ param.value }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import Table from './connection-data/Table.vue'
import Data from './connection-data/Data.vue'
import api from '@/api'
import util from '@/util'
export default {
  props: {
    connectionId: {
      type: String,
      default: ''
    }
  },
  components: { Table, Data },
  data() {
    return {
      tabIndex: 'table',
      drawerVisible: false,
      connection: {
        running: true
      },
      tables: [],
      tablePanes: []
    }
  },
  computed: {
    params() {
      const params = this.connection.params ?? {}
      const list = []
      for (const [name, value] of Object.entries(params)) {
        list.push({ name, value })
      }
      return list
    },
    ...mapGetters({
      connections: 'global/getConnections'
    })
  },
  watch: {},
  methods: {
    async refreshConnections() {
      const resp = await api.connection.getAllConnection()
      if (resp.ok) {
        this.setConnections(resp.data ?? [])
      } else {
        this.$message({ message: resp.message, type: 'error', duration: 1500 })
      }
    },
    async refreshTables() {
      const resp = await api.table.listTable(this.connectionId)
      if (resp.ok) {
        this.tables = JSON.parse(JSON.stringify(resp.data ?? []))
      } else {
        this.$message({ message: resp.message, type: 'error', duration: 1500 })
      }
    },
    async closeConnection() {
      const resp = await api.connection.deleteConnectionById(this.connection.id)
      if (resp.ok) {
        this.$message({ message: '已成功关闭连接', type: 'info', duration: 1000 })
        await this.refreshConnections()
      } else {
        this.$message({ message: resp.message, type: 'error', duration: 1500 })
      }
    },
    openTable(tableName) {
      const tablePanes = JSON.parse(JSON.stringify(this.tablePanes))
      for (const tablePane of tablePanes) {
        if (tableName === tablePane.name) {
          this.tabIndex = tablePane.tabIndex
          return
        }
      }
      for (const table of this.tables) {
        if (table.name === tableName) {
          const tablePane = {
            tabIndex: `table-${tableName}`,
            name: tableName,
            families: table.families,
            table: table
          }
          tablePanes.push(tablePane)
          this.tablePanes = tablePanes
          this.tabIndex = tablePane.tabIndex
          return
        }
      }
    },
    closeTable(tabIndex) {
      const tablePanes = JSON.parse(JSON.stringify(this.tablePanes))
      const list = []
      for (const tablePane of tablePanes) {
        if (tabIndex !== tablePane.tabIndex) {
          list.push(tablePane)
        }
      }
      if (list.length > 0) {
        this.tabIndex = list[0].tabIndex
      } else {
        this.tabIndex = 'table'
      }
      this.tablePanes = list
    },
    setTables(tables) {
      this.tables = JSON.parse(JSON.stringify(tables))
    },
    copyText(text) {
      util.copyText(text)
      this.$message({ message: `已复制：${text}`, type: 'info', duration: 1000 })
    },
    formatTimestampString(timestampString) {
      return util.formatTimestamp(timestampString)
    },
    ...mapActions({
      setConnections: 'global/setConnections'
    })
  },
  beforeCreate() { },
  async created() {
    await this.refreshConnections()
    const connections = this.connections
    for (const connection of connections) {
      if (connection.id === this.connectionId) {
        this.connection = JSON.parse(JSON.stringify(connection))
        break
      }
    }
    await this.refreshTables()
  },
  beforeDestroy() { },
  destroyed() { }
}
</script>
<style lang="scss" scoped>
@use '../../../assets/scss/var.scss' as *;

.connection-data {
  padding: 16px;

  .success-status {
    height: 32px;
    line-height: 32px;

    &::before {
      content: '';
      width: 16px;
      height: 16px;
      line-height: 32px;
      margin-right: 10px;
      vertical-align: text-bottom;
      display: inline-flex;
      border-radius: 50%;

      @include useTheme {
        background-color: getVar('success-color');
      }
    }
  }

  .error-status {
    height: 32px;
    line-height: 32px;

    &::before {
      content: '';
      width: 16px;
      height: 16px;
      line-height: 32px;
      margin-right: 10px;
      vertical-align: text-bottom;
      display: inline-flex;
      border-radius: 50%;

      @include useTheme {
        background-color: getVar('error-color');
      }
    }
  }

  .connection-info {
    margin-left: 10px;
    height: 32px;
    line-height: 32px;
  }

  @include useTheme {
    background-color: getVar('background-color');
  }
}

::v-deep {
  .el-descriptions .is-bordered .el-descriptions-item__cell {
    padding: 0;

    .value {
      padding-left: 20px;
      padding-right: 20px;
      display: block;
      line-height: 48px;
      text-align: start;
    }

    &.el-descriptions-item__label {
      padding-left: 20px;
      padding-right: 20px;
      line-height: 48px;
      text-align: start;
    }
  }
}
</style>